const { Financial, FinancialOperation, FinancialProfit, FinancialProfitYear } = require('../models/financial');

/**
 * 理财产品服务类
 */
class FinancialService {
  /**
   * 获取理财产品列表
   * @returns {Promise<Array<Financial>>}
   */
  async getFinancialList() {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'financial',
        data: {
          action: 'getList'
        }
      });
      if (result.code === 200) {
        return result.data.map(item => new Financial(item));
      }
      return [];
    } catch (error) {
      console.error('获取理财产品列表失败:', error);
      return [];
    }
  }

  /**
   * 获取理财产品详情
   * @param {string} id 产品ID
   * @returns {Promise<Financial|null>}
   */
  async getFinancialDetail(id) {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'financial',
        data: {
          action: 'getDetail',
          data: { id }
        }
      });
      
      if (result.code === 200) {
        return new Financial(result.data);
      }
      return null;
    } catch (error) {
      console.error('获取理财产品详情失败:', error);
      return null;
    }
  }

  /**
   * 添加理财产品
   * @param {Financial} financial 产品信息
   * @returns {Promise<boolean>}
   */
  async addFinancial(financial) {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'financial',
        data: {
          action: 'add',
          data: financial
        }
      });
      
      return result.code === 200;
    } catch (error) {
      console.error('添加理财产品失败:', error);
      return false;
    }
  }

  /**
   * 更新理财产品
   * @param {Financial} financial 产品信息
   * @returns {Promise<boolean>}
   */
  async updateFinancial(financial) {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'financial',
        data: {
          action: 'update',
          data: financial.toApiFormat()
        }
      });
      
      return result.code === 200;
    } catch (error) {
      console.error('更新理财产品失败:', error);
      return false;
    }
  }

  /**
   * 删除理财产品
   * @param {string} id 产品ID
   * @returns {Promise<boolean>}
   */
  async deleteFinancial(id) {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'financial',
        data: {
          action: 'delete',
          data: { id }
        }
      });
      
      return result.code === 200;
    } catch (error) {
      console.error('删除理财产品失败:', error);
      return false;
    }
  }

  /**
   * 添加操作记录
   * @param {FinancialOperation} operation 操作记录
   * @returns {Promise<boolean>}
   */
  async addOperation(operation) {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'financial',
        data: {
          action: 'addOperation',
          data: operation.toApiFormat()
        }
      });
      
      return result.code === 200;
    } catch (error) {
      console.error('添加操作记录失败:', error);
      return false;
    }
  }

  /**
   * 添加收益记录
   * @param {FinancialProfit} profit 收益记录
   * @returns {Promise<boolean>}
   */
  async addProfit(profit) {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'financial',
        data: {
          action: 'addProfit',
          data: profit.toApiFormat()
        }
      });
      
      return result.code === 200;
    } catch (error) {
      console.error('添加收益记录失败:', error);
      return false;
    }
  }

  /**
   * 获取年度收益统计
   * @param {number} year 年份
   * @returns {Promise<Array<FinancialProfitYear>>}
   */
  async getYearlyProfit(year) {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'financial',
        data: {
          action: 'getYearlyProfit',
          data: { year }
        }
      });
      
      // if (result.code === 200) {
      //   return result.data.map(item => new FinancialProfitYear(item));
      // }
      return [];
    } catch (error) {
      console.error('获取年度收益统计失败:', error);
      return [];
    }
  }

  /**
   * 获取产品操作历史
   * @param {string} financialId 产品ID
   * @returns {Promise<Array<FinancialOperation>>}
   */
  async getOperationHistory(financialId) {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'financial',
        data: {
          action: 'getOperationHistory',
          data: { financialId }
        }
      });
      
      if (result.code === 200) {
        return result.data.map(item => new FinancialOperation(item));
      }
      return [];
    } catch (error) {
      console.error('获取操作历史失败:', error);
      return [];
    }
  }

  /**
   * 获取产品收益历史
   * @param {string} financialId 产品ID
   * @returns {Promise<Array<FinancialProfit>>}
   */
  async getProfitHistory(financialId) {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'financial',
        data: {
          action: 'getProfitHistory',
          data: { financialId }
        }
      });
      
      if (result.code === 200) {
        return result.data.map(item => new FinancialProfit(item));
      }
      return [];
    } catch (error) {
      console.error('获取收益历史失败:', error);
      return [];
    }
  }

  /**
   * 导出数据
   * @param {number} year 年份
   * @returns {Promise<Object>}
   */
  async exportData(year) {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'financial',
        data: {
          action: 'exportData',
          data: { year }
        }
      });
      
      if (result.code === 200) {
        // 生成CSV文件内容（关键修改：buy_date -> buyDate；end_date -> endDate）
        const { products, profits, operations } = result.data;
        
        // 产品数据
        let productsCSV = '产品名称,理财机构,产品类型,投资金额,当前收益,年化收益率,购买日期,到期日期,备注\n';
        products.forEach(product => {
          productsCSV += `${product.name},${product.bank},${product.type},${product.money},${product.profit},${product.arr},${product.buyDate},${product.endDate || ''},${product.remark || ''}\n`;  // 原 buy_date、end_date 改为 buyDate、endDate
        });

        // 收益记录
        let profitsCSV = '产品ID,收益金额,年化收益率,记录日期\n';
        profits.forEach(profit => {
          profitsCSV += `${profit.financial_id},${profit.profit},${profit.arr},${profit.submit_date}\n`;
        });

        // 操作记录
        let operationsCSV = '产品ID,操作类型,操作金额,操作日期\n';
        operations.forEach(operation => {
          operationsCSV += `${operation.financial_id},${operation.type},${operation.money},${operation.submit_date}\n`;
        });

        // 保存文件
        const fs = wx.getFileSystemManager();
        const productsPath = `${wx.env.USER_DATA_PATH}/products_${year}.csv`;
        const profitsPath = `${wx.env.USER_DATA_PATH}/profits_${year}.csv`;
        const operationsPath = `${wx.env.USER_DATA_PATH}/operations_${year}.csv`;

        await Promise.all([
          new Promise((resolve, reject) => {
            fs.writeFile({
              filePath: productsPath,
              data: productsCSV,
              encoding: 'utf8',
              success: resolve,
              fail: reject
            });
          }),
          new Promise((resolve, reject) => {
            fs.writeFile({
              filePath: profitsPath,
              data: profitsCSV,
              encoding: 'utf8',
              success: resolve,
              fail: reject
            });
          }),
          new Promise((resolve, reject) => {
            fs.writeFile({
              filePath: operationsPath,
              data: operationsCSV,
              encoding: 'utf8',
              success: resolve,
              fail: reject
            });
          })
        ]);

        return {
          products: productsPath,
          profits: profitsPath,
          operations: operationsPath
        };
      }
      return null;
    } catch (error) {
      console.error('导出数据失败:', error);
      return null;
    }
  }

  /**
   * 获取年度统计数据（迁移至云函数）
   * @param {number} year 年份
   * @returns {Promise<Object>}
   */
  async getYearlyStats(year) {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'financial',
        data: {
          action: 'getYearlyStats',  // 新增云函数 action
          data: { year }
        }
      });
      return result.code === 200 ? result.data : { profit: 0, rate: 0 };
    } catch (error) {
      console.error('获取年度统计数据失败:', error);
      return { profit: 0, rate: 0 };
    }
  }

  /**
   * 获取月度统计数据（迁移至云函数）
   * @param {number} year 年份
   * @returns {Promise<Array>}
   */
  async getMonthlyStats(year) {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'financial',
        data: {
          action: 'getMonthlyStats',  // 新增云函数 action
          data: { year }
        }
      });
      return result.code === 200 ? result.data : new Array(12).fill({ profit: 0, rate: 0 });
    } catch (error) {
      console.error('获取月度统计数据失败:', error);
      return new Array(12).fill({ profit: 0, rate: 0 });
    }
  }

  /**
   * 获取类型统计数据（迁移至云函数）
   * @param {number} year 年份
   * @returns {Promise<Object>}
   */
  async getTypeStats(year) {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'financial',
        data: {
          action: 'getTypeStats',  // 新增云函数 action
          data: { year }
        }
      });
      return result.code === 200 ? result.data : { fund: 0, deposit: 0, financial: 0 };
    } catch (error) {
      console.error('获取类型统计数据失败:', error);
      return { fund: 0, deposit: 0, financial: 0 };
    }
  }

  /**
   * 获取操作记录列表
   * @param {Object} params 查询参数
   * @returns {Promise<Object>}
   */
  async getOperationList(params) {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'financial',
        data: {
          action: 'getOperationList',
          data: params
        }
      });
      
      if (result.code === 200) {
        return {
          list: result.data.list.map(item => ({
            ...item,
            productName: item.financial ? item.financial.name : '未知产品'
          })),
          total: result.data.total
        };
      }
      return {
        list: [],
        total: 0
      };
    } catch (error) {
      console.error('获取操作记录列表失败:', error);
      return {
        list: [],
        total: 0
      };
    }
  }
}

module.exports = new FinancialService();